import React from "react";
import { useHistory } from "react-router-dom";
import { Form, Input, Button, Checkbox, Row, Col, message } from "antd";
import { loginMange } from "../services/login";
import { setToken } from "../utils/tool";

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 8,
    span: 16,
  },
};

const Login = () => {
  const history = useHistory();
  const onFinish = async (values) => {
    const res = await loginMange(values);
    if (res.code === 1) {
      message.success("登录成功");
      setToken(res.data);
      history.push("/main/products");
    } else {
      message.error(res.data);
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <Row>
      <h1 style={{ width: "100vw", textAlign: "center", marginTop: 20 }}>
        夕阳后台管理
      </h1>
      <Col span={8} push={7} style={{ marginTop: 20 }}>
        <Form
          {...layout}
          name="basic"
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="用户名"
            name="userName"
            rules={[
              {
                required: true,
                message: "请输入用户名",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: "请输入密码",
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item {...tailLayout} name="remember" valuePropName="checked">
            <Checkbox>记住密码</Checkbox>
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Col>
    </Row>
  );
};

export default Login;
